import threading
import time
import dpkt
from netFunctions import its,mts

class ArpSpy(threading.Thread):
    def __init__(self,interface,inputbuffer,arptable):
        threading.Thread.__init__(self)
        self._buffer = inputbuffer
        self._outputInterface = interface
        self._running = False
        self._arpTable = arptable
        
    def stop(self):
        self._running = False
        
    def isRunning(self):
        return self._running
    
    def _bufferEmpty(self):
        if self._buffer.length() > 0:
            return False
        else:
            return True
        
    def _getDataFromBuffer(self):
        if self._bufferEmpty():
            return []
        else:
            data = self._buffer.getItems(-1)
            return data
    
    def run(self):
        self._running = True
        while self.isRunning():
            for item in self._getDataFromBuffer():
                if item.type == dpkt.ethernet.ETH_TYPE_ARP:
                    if item.data.op == 2:
                        self._arpTable.insert({item.data.spa:item.data.sha})
                        for key in self._arpTable.getcontent("dict"):
                            print its(key)+"\tis\t"+mts(self._arpTable.getcontent("dict")[key])
            time.sleep(0.01)
